
import React,{Component} from "react";
import { Button, Form, Input, Radio, DatePicker, message} from "antd";
import moment from "moment";
import ajax from '../../ajaxMethod';

class PersonalInf extends Component{
    constructor(props){
        super(props);
        this.state = {
            username: localStorage.getItem("username"),
            state: "0",//0：显示信息不能修改，1：修改信息
            values:{
                username: localStorage.getItem("username"),
                email: "",
                gender: 0,
                birthday: "2015-01-01",
            },
            repeatTestState: 0,
            nameExist: false,
            time: 0,
        }
    }
    componentDidMount(){
        this.init();
    }
    init = () =>{
        let _this = this;
        ajax.getAjax("/interface/personalInf",{username: this.state.username}, res=>{
            if(res.success){
                console.log("要设置的",res,{..._this.state.values, ...res.data});
                _this.setState({values: {..._this.state.values, ...res.data}});
            }else{
                console.error(res.description);
                message.success(res.description);
            }
        },err=>{
            console.error(err);
        })
    }
    saveClick = (e) =>{
        if(this.state.state === "0"){
            //可以编辑
            this.setState({state:"1"});
        }else{
            //ajax检验信息后提交
            let values = this.props.form.getFieldsValue(),
                flag = false,//是否有空的
                _this = this;
            if(this.state.repeatTestState === 1){//用户名重复检测不通过不能提交
                message.warning("请先进行用户名重复检测");
            }else{
                for(let item in values){
                    if(!item){
                        flag = true;
                        break;
                    }
                }
                console.log("values", values, flag);
                if(flag){
                    message.error("所有信息都须填写");
                }else{
                    values.birthday = values.birthday.format("YYYY-MM-DD");
                    values._id = this.state.values._id;
                    ajax.postAjax("/interface/userChange", values, res=>{
                        if(res.success){
                            message.success("修改成功");
                            //修改本地保存的用户名,暂时不允许修改用户名.
                            // localStorage.setItem("username", this.state.username);
                            _this.setState({ state: "0", repeatTestState: 0, nameExist: false });
                        }else{
                            message.success("修改失败");
                        }
                    });
                }
            }
        }
    }
    cancleClick = (e) =>{
        this.setState({ state: "0", repeatTestState: 0,});
        this.init();
    }
    handleValidatorName = (rule, val, callback) =>{
        if(val){
            val = val.replace(/\s+/g, "");
            if(!val){ callback("用户名不能为空"); }
            let reg = new RegExp(/([\u4e00-\u9fa5]|[a-z]|[A-Z]|[0-9]){4,16}/);
            if(reg.test(val)){
                this.setState({repeatTestState: 1});
            }
            else{
                callback("请输入4-16位字符的用户名并进行重复检测");
            }
        }else{
            callback("用户名不能有空格");
        }
    }
    userNameChange = (e) => {
        this.setState({nameExist :true});
    }
    repeatTest = (e) => {
        let username = this.props.form.getFieldValue("username"),
            blank = false,
            _this = this.componentWillUpdate;

        for(let i= 0; i < username.length; i++){
            if(' ' === username[i]){
                blank = true;
                break;
            }
        }
        if(blank === true){
            message.error("用户名不能含有空格");
        }
        else{
            //从后台检测这个用户名是否存在
            this.setState({time: 6});
            ajax.getAjax("/interface/usernameRepeatTest", {username: this.state.username}, res=>{
                if(res.success){
                    if(res.data.state === 1){
                        _this.setState({nameExist: false, repeatTestState: 0});
                        message.success("用户名检测成功");
                    }else{//用户名重复
                        _this.setState({nameExist: true});
                        message.warning("用户名重复");
                    }
                }else{
                    console.error(res.description);
                    message.error(res.description);
                }
            })
            for(let i = 0; i < 6; i++){
                setTimeout(() => {
                    this.setState({time: this.state.time - 1});
                }, i * 1000);
            }
            setTimeout(() => {
                this.setState({repeatTestState: 0});
            }, 5000);
        }
    }
    handleValidator = (rule, val, callback) =>{
        if(!val){ callback(); }
        let regEmail = new RegExp(/^[\w.\-]+@(?:[a-z0-9]+(?:-[a-z0-9]+)*\.)+[a-z]{2,3}$/);

        if(!regEmail.test(val)){
            callback("请输入正确的邮箱");
            this.setState({getCodeState: 0});
        }else{
            this.setState({getCodeState: 1});
        }
    }
    disabledDate = (current)=> {
        // 只能选择今天之前的
        return current && current > moment().endOf('day');
    }
    render(){
        console.log("state--personal", this.state);
        const state = this.state;
        const {getFieldProps, getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
                //sm是表示从横坐标的6开始，24表示总共有2个
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
                //sm表示宽度
            },
        };
        const afterfix = 
        // getFieldDecorator('repeat-test-btn')(
            <button id="repeat-test-btn" disabled={state.state === "0" | this.state.repeatTestState === 0 || this.state.time?true:false} onClick={this.repeatTest} >
                { !this.state.time? "重复检测": this.state.time + " 秒" }
            </button>
        // )
        const isdisabled = state.state === "0"?true:false;
        const valid = isdisabled?{validateStatus:"success"}:{validateStatus:state.repeatTestState === 1?"warning":"success"};
        return(
        <div className="personal-inf">
            <div className="contral">
                {state.state === "0"?<Button onClick={this.saveClick}>修改</Button>: <Button onClick={this.saveClick} className="save">保存</Button>}
                {state.state === "0"?[]:<Button onClick={this.cancleClick}>取消</Button>}
            </div>
            <Form>
                <Form.Item
                    {...formItemLayout}
                    label="用户名"
                    {...valid}
                    hasFeedback
                    >
                    <Input 
                        disabled={true}
                        addonAfter={afterfix} placeholder='请输入4-16个字母/数字/汉字' 
                        {...getFieldProps('username', {
                            rules: [
                                {required: true, message: '请输入四个字符以上的用户名并进行重复检测' },
                                {validator: this.handleValidatorName}
                            ],
                            initialValue:state.values.username,
                        })} />
                </Form.Item>
                <Form.Item
                    {...formItemLayout}
                    label="邮箱号"
                    >
                    <Input disabled={isdisabled}
                        {...getFieldProps('email', {
                            rules: [
                                {required: true, message: '请输入邮箱' },
                                {validator: this.handleValidator}
                            ],
                            initialValue:state.values.account,
                        })} />
                </Form.Item>
                <Form.Item 
                    label="性别" 
                    {...formItemLayout} 
                    >
                        <Radio.Group  
                            disabled={isdisabled}  
                            name="radiogroup1" 
                            onChange={this.radioChange}
                            {...getFieldProps('gender',{
                                initialValue: state.values.gender,
                            })}>
                            <Radio value={0}>男</Radio>
                            <Radio value={1}>女</Radio>
                        </Radio.Group >
                </Form.Item>
                <Form.Item
                    {...formItemLayout}
                    label="出生日期"
                    >
                    <DatePicker 
                        disabled={isdisabled}  
                        disabledDate={this.disabledDate} 
                        placeholder="请选择日期" 
                        defaultValue={moment('2015/01/01', 'YYYY-MM-DD')} 
                        {...getFieldProps('birthday', {
                            initialValue: moment(state.values.birthday, 'YYYY-MM-DD'),
                            rules: [{
                                required: true, message: '请输入出生日期',
                            }],
                        })}></DatePicker >
                </Form.Item>
            </Form>
        </div>)
    }
}
export default Form.create({})(PersonalInf);